package com.sqly.doc.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServicePackage;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class TimerService extends Service {
    private static String token;
    private static String ruid;
    private boolean pushthread = false;
    private List<String> gridList = new ArrayList<>();

    public TimerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("TimerService", "onBind");
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TimerService", "onStartCommand");
        if (intent != null) {
            if (intent.getStringExtra("flags").equals("3")) {
                //判断当系统版本大于20，即超过Android5.0时，我们采用线程循环的方式请求。
                //当小于5.0时的系统则采用定时唤醒服务的方式执行循环
                int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                if (currentapiVersion > 20) {
                    getPushThread();
                } else {
                    getGrjbxxByNet();
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //循环请求的线程
    public void getPushThread() {
        pushthread = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (pushthread) {
                    try {
                        Thread.sleep(30000);
                        getGrjbxxByNet();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //请求网络获取数据
    private void getGrjbxxByNet() {
            RequestParams ps = new RequestParams();
            ps.add("token", token);
            ps.add("type", "2");
            ps.add("page", 1 + "");
            ps.add("pageSize", 30+"");
            ps.add("ruid", ruid);
            UserClient.get(HttpUrl.syncJbxxUserList, ps, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                    Log.i("getGrjbxxByNet","请求失败");
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                    String content = new String(response);
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if (ret.getCode().equals("200")) {
                        List<JuMin> uList = JSON.parseArray(ret.getList(), JuMin.class);
                        if(null != uList ) {
                            for (int i = 0; i < uList.size(); i++) {
                                JuMin jm = uList.get(i);
                                List<JuMin> localList = DataSupport.where("JKDAH = ?", jm.getJKDAH()).find(JuMin.class);
                                if (localList.size() > 0) {//如果本地已存在，先删除
                                    localList.get(0).delete();
                                }
                                jm.save();
                                if(!gridList.contains(jm.getJKDAH())){
                                    gridList.add(jm.getJKDAH());
                                }
                            }
                            upGrjbxxRecord(gridList);
                        }
                    } else {
                        Log.i("getGrjbxxByNet","获取错误");
                    }
                }
            });
    }

    //请求网络获取数据
    private void upGrjbxxRecord(List<String> gridList) {
        RequestParams ps = new RequestParams();
        ps.add("token", token);
        ps.add("type", "2");
        ps.add("ruid", ruid);
        for (String grid : gridList) {
            ps.add("grid", grid);
        }
        UserClient.get(HttpUrl.syncJbxxUser, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                Log.i("upGrjbxxRecord","请求失败");
            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    Log.i("upGrjbxxRecord",ret.getCode());
                } else {
                    Log.i("upGrjbxxRecord","获取错误");
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        pushthread = false;
        Log.d("TimerService", "onDestroy");
        super.onDestroy();
    }

    //启动服务和定时器
    public static void getConnet(Context mContext) {
        try {
            Intent intent = new Intent(mContext, TimerService.class);
            intent.putExtra("flags", "3");
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            token = SharedPreferencesUtils.getParam(mContext, "token", "").toString();
            ruid = SharedPreferencesUtils.getParam(mContext, "ruid", "").toString();
            if (currentapiVersion > 20) {
                //一般的启动服务的方式
                mContext.startService(intent);
            } else {
                //定时唤醒服务的启动方式
                PendingIntent pIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 3000, pIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //停止由AlarmManager启动的循环
    public static void stop(Context mContext) {
        Intent intent = new Intent(mContext, TimerService.class);
        PendingIntent pIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pIntent);
    }
}